<template>
  <div class="role-alloc-resource">
    <!-- card基础用法 -->
    <el-card
      class="box-card"
      v-for="category in roleResourceData"
      :key="category.id"
    >
      <div slot="header" class="clearfix">
        <!-- checkbox复选框 indeterminate 状态 -->
        <!-- checkbox的头部 -->
        <el-checkbox
          :indeterminate="category.isIndeterminate"
          v-model="category.selected"
          @change="handleCheckAllChange(category)"
          >{{ category.name }}</el-checkbox
        >
        <!-- <div style="margin: 15px 0"></div> -->
      </div>
      <!-- checkbox分组内容 -->
      <el-checkbox-group
        v-model="category.checkedResourceIds"
        @change="handleCheckedResourceChange(category)"
      >
        <!-- 一行显示3个 -->
        <el-row>
          <el-col
            :span="8"
            v-for="resource in category.resourceList"
            :key="resource.id"
          >
            <!-- checkbox -->
            <el-checkbox :label="resource.id" style="padding: 7px 0px">
              {{ resource.name }}
            </el-checkbox>
          </el-col>
        </el-row>
      </el-checkbox-group>
    </el-card>
    <div class="footer-btn">
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-button @click="onClear">清空</el-button>
    </div>
  </div>
</template>

<script>
import { getRoleResources, setRoleResources } from "@/api/role";

export default {
  name: "RoleAllocResource",
  props: {
    roleId: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      roleResourceData: [],
    };
  },
  created() {
    this.loadRoleResources();
  },
  methods: {
    //获取角色拥有的资源信息
    loadRoleResources() {
      getRoleResources(this.roleId).then((res) => {
        if (res.data.code === "000000") {
          console.log("获取角色拥有的资源信息", res);
          this.roleResourceData = res.data.data
            .map((category) => {
              //roleResourceData数据瘦身得到类别category
              let { id, name, resourceList, selected, sort } = category;
              //category瘦身得到资源resource
              const checkedResourceIds = []; //记录当前类别下被选中的资源id
              const allResourceIds = []; //记录当前类别下所有的资源id
              //const isIndeterminate = false; //表示类别是否显示为“减号-”
              resourceList = resourceList?.map((resource) => {
                const { id, name, selected, url, description } = resource;
                //   if (selected) checkedResourceIds.push(id);
                selected && checkedResourceIds.push(id);
                allResourceIds.push(id);
                return { id, name, selected, url, description };
              });
              //表示类别是否显示为“减号-”
              const isIndeterminate =
                checkedResourceIds.length > 0 &&
                checkedResourceIds.length < allResourceIds.length;
              //修正category类别选中状态selected
              selected = checkedResourceIds.length === allResourceIds.length;
              return {
                id,
                name,
                resourceList,
                selected,
                sort,
                //添加的自定义属性
                checkedResourceIds,
                allResourceIds,
                isIndeterminate,
              };
            })
            .sort((c1, c2) => c1.id - c2.id);
        } else {
          this.$message.error("获取角色拥有的资源信息失败...");
        }
      });
    },
    //全选（全不选）
    handleCheckAllChange(category) {
      category.checkedResourceIds = category.selected
        ? category.allResourceIds
        : [];
      category.isIndeterminate = false;
    },
    //子选框
    handleCheckedResourceChange(category) {
      let checkedCount = category.checkedResourceIds.length;
      const totalCount = category.allResourceIds.length;
      category.selected = checkedCount === totalCount;
      category.isIndeterminate = checkedCount > 0 && checkedCount < totalCount;
    },
    //清空
    onClear() {
      this.roleResourceData.forEach((category) => {
        category.checkedResourceIds = [];
        category.selected = false;
      });
    },
    //保存
    onSave() {
      const { roleId, roleResourceData } = this;
      const resourceIdList = roleResourceData.reduce((res, category) => {
        return res.concat(category.checkedResourceIds);
      }, []);
      setRoleResources({ roleId, resourceIdList }).then((res) => {
        if (res.data.code === "000000") {
          this.$message.success("给角色分配资源成功!");
          this.$router.push({ name: "roles" });
        } else {
          this.$message.error("给角色分配资源失败...");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.footer-btn {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.el-card {
  margin-bottom: 20px;
}
</style>
